package com.itheima.d06_singleton;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class Test {
    public static void main(String[] args) throws Exception {
        //问题1：反射破坏单例
        /*Class<SingleModel> cls = SingleModel.class;

        Constructor<SingleModel> constructor = cls.getDeclaredConstructor();
        constructor.setAccessible(true);

        SingleModel singleModel = constructor.newInstance();
        System.out.println(singleModel);


        SingleModel singleModel2 = constructor.newInstance();
        System.out.println(singleModel2);*/

        //问题2：序列化破坏单例
        /*
            当对象被反序列化时：
                jvm会创建一个新的对象，不使用构造器创建的对象
                jvm会通过字节流中的数据填充出一个新的对象的所需的数据
         */
        SingleModel instance = SingleModel.getInstance();
        System.out.println("第一个对象："+ instance );

        //把单例对象，写入到字节数组输出流中
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(instance);

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        SingleModel instance2 = (SingleModel) ois.readObject();
        System.out.println("第二个对象："+ instance2);



    }
}
